package com.jx.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.dao.system.RoleMenuDao;
import com.jx.pojo.entity.system.Role;
import com.jx.pojo.entity.system.RoleMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RoleMenuService extends ServiceImpl<RoleMenuDao, RoleMenu> {


    /**
     * 批量新增角色菜单关联表
     */
    @Transactional
    public void saveRoleMenu(Role role,List<Integer> menuIds) {

        Integer roleId = role.getId();

        // 删除旧数据
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        this.remove(wrapper);

        // 保存新数据
        List<RoleMenu> list = new ArrayList<>();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            list.add(roleMenu);
        }
         this.saveBatch(list);
    }

    public List<Integer> getMenuIdsByRoleId(Integer roleId) {
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        List<RoleMenu> list = this.list(wrapper);
        List<Integer> menuIds = new ArrayList<>();
        for (RoleMenu roleMenu : list) {
            menuIds.add(roleMenu.getMenuId());
        }
        return menuIds;
    }

    @Transactional
    public void deleteByRoleId(Integer roleId) {
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        this.remove(wrapper);
    }

}
